using System.Collections;
using Commons.Injector;
using Commons.Models.Settings;
using System;

namespace Commons.Loading
{
	public class ContextLoadingTask : BasicLoadingTask
	{
		private ContextParser contextParser;

		public ContextLoadingTask(float weight) : base(weight)
		{

		}

		public override void SetUp()
		{
			if (! Context.Instance.Initialized)
			{
				contextParser = new ContextParser();
			}
		}

		public override IEnumerator Update()
		{
			if (Context.Instance.Initialized)
			{
				Console.WriteLine("Context already initialized");
			}
			else
			{
                Console.WriteLine("Start parsing context...");
				IEnumerator parseEnum = contextParser.Parse();
				while(parseEnum.MoveNext())
				{
					yield return parseEnum.Current;
				}
                Console.WriteLine("End parsing context...");

				while (SettingsModel.Instance == null)
				{
					yield return null;
				}

                Console.WriteLine("Start initializing context...");
				IEnumerator initEnum = Context.Instance.Initialize();
				while(initEnum.MoveNext())
				{
					yield return initEnum.Current;
				}
                Console.WriteLine("End initialize context");
			}
            /*
            Console.WriteLine("Start loading scope...");
			IEnumerator loadEnum = Context.Instance.LoadScopeSync(Application.loadedLevelName);
			while(loadEnum.MoveNext())
			{
				yield return loadEnum.Current;
			}
            Console.WriteLine("End loading scope...");
            */
			Completed = true;
		}

		public override float Progress
		{ 
			get
			{
				if (Completed)
				{
					return 1.0f;
				}
				else
				{
					float parseProgress = 0.0f;
					if (contextParser != null && contextParser.TotalObjects > 0)
					{
						parseProgress = (float) contextParser.NumObjects / contextParser.TotalObjects;
					}

					float initProgress = 0.0f;
					if (Context.Instance.TotalInitSteps > 0)
					{
						initProgress = (float) Context.Instance.NumInitSteps / Context.Instance.TotalInitSteps;
					}

					float loadProgress = 0.0f;
					if (Context.Instance.TotalLoadSteps > 0)
					{
						loadProgress = (float) Context.Instance.NumLoadSteps / Context.Instance.TotalLoadSteps;
					}

					return (parseProgress + initProgress + loadProgress) / 3.0f;
				}
			}
		}
	}
}

